<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Call Backend API with EventSource</title>
</head>

<body>
<button onclick="init()">点击连接</button>
<div id="messages"></div>
<script>

    function init() {
        // 创建 EventSource 实例，指定后端接口的 URL
        const eventSource = new EventSource('http://localhost:8080/chat-sse?message=hello');

        // 当连接成功打开时触发
        eventSource.onopen = function () {
            console.log('连接已打开');
            const messageDiv = document.createElement('p');
            messageDiv.innerHTML = "连接已打开"
            document.getElementById('messages').appendChild(messageDiv);
        };

        // 当接收到消息时触发
        eventSource.onmessage = function (event) {
            console.log("接收到消息：" + event.data);
            try {
                // 解析接收到的消息数据
                const chatMessage = JSON.parse(event.data);
                // 假设 ChatMessage 对象有一个 text 属性，将消息显示在页面上
                const messageDiv = document.createElement('p');
                messageDiv.innerHTML = chatMessage.content
                document.getElementById('messages').appendChild(messageDiv);
            } catch (error) {
                //console.error('解析消息数据时出错:', error);
                const messageDiv = document.createElement('p');
                messageDiv.innerHTML = event.data
                document.getElementById('messages').appendChild(messageDiv);
            }
        };

        // 当发生错误时触发
        eventSource.onerror = function (error) {
            console.error('连接出错:', error);
            const messageDiv = document.createElement('p');
            messageDiv.innerHTML = "连接出错" + error.message
            document.getElementById('messages').appendChild(messageDiv);
            // 关闭连接
            eventSource.close();
        };

    }
</script>
</body>

</html>    